<template>
  <div class="page-miH page-bgBack">
    <PageHeader @back="$router.go(-1)" subTitle="返回"> 今日新增 </PageHeader>
    <a-layout class="p24">
      <div class="t-row">
        <div class="t-col" @click="onScreening(0)">
          今日新增：<span>{{ allCount }}人</span>
        </div>
        <div class="t-col" @click="onScreening(1)">
          网页端录入：<span>{{ pcCount }}人</span>
        </div>
        <div class="t-col" @click="onScreening(2)">
          手机端录入：<span>{{ appCount }}人</span>
        </div>
        <div class="t-col" @click="onScreening(3)">
          更换用工单位：<span>{{ changeCount }}人</span>
        </div>
      </div>
      <div
        style="
          margin-top: 24px;
          margin-bottom: 24px;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div>
          <a-input-search
            v-model="nameOrPhoneOrCard"
            allow-clear
            class="mr12"
            placeholder="姓名/手机号/身份证号"
            style="width: 180px"
            @search="getData(true)"
          />
          <a-input-search
            v-model="inputName"
            allow-clear
            placeholder="录入人"
            style="width: 180px; margin-right: 12px"
            @search="getData(true)"
          />
          <a-select v-model="sortType" class="mr12" style="width: 136px" placeholder="员工排序" allow-clear @change="getData(true)">
            <a-select-option v-for="(item, index) in staffSort" :key="index" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
          <a-date-picker
            v-model="time"
            valueFormat="YYYY-MM-DD"
            placeholder="选择日期"
            style="width: 136px"
            :allow-clear="false"
            @change="getData(true)"
          />
        </div>
        <div>
          <a-button :disabled="!selectedRowKeys.length" class="mr12" @click="() => download(1)">批量导出</a-button>
          <a-button :disabled="!data.length" class="mr12" @click="() => download(2)">全部导出</a-button>
          <a-dropdown>
            <a-menu slot="overlay" @click="handleMenuchange">
              <a-menu-item key="1">批量导入员工</a-menu-item>
              <a-menu-item key="2">批量导入合同</a-menu-item>
            </a-menu>
            <a-button class="mr12">
              批量导入
              <a-icon type="caret-down" />
            </a-button>
          </a-dropdown>
          <a-button icon="plus" type="primary" @click="addMember">添加员工</a-button>
        </div>
      </div>
      <a-modal v-model="chooseVisible" title="批量导入目的" width="600px" :footer="null">
        <a-button class="chooseBox" @click="chooseOk(1)">
          <div class="choose">
            <div class="chooseTitle">批量导入新员工</div>
            <div class="chooseContent">适用于首次使用花名册新增员工，仅支持导入花名册中没有的员工，仅支持导入在职员工。</div>
          </div>
          <a-icon type="right" />
        </a-button>
        <a-button class="chooseBox" style="margin-top: 18px" @click="chooseOk(2)">
          <div class="choose">
            <div class="chooseTitle">批量修改员工信息</div>
            <div class="chooseContent">适用于批量更新，仅修改花名册已有的员工的信息。</div>
          </div>
          <a-icon type="right" />
        </a-button>
      </a-modal>
      <a-table
        :columns="columns"
        :data-source="data"
        row-key="id"
        :scroll="{ x: 800 }"
        tip="加载中..."
        :loading="loading"
        :pagination="pagination"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange
        }"
        @change="handleTableChange"
      >
        <span slot="name" slot-scope="text, record">
          <div class="today-tags">
            <div class="tags-item" style="background: #ffbb02" v-if="record.status == 1">待入职</div>
            <div class="tags-item" style="background: #b9b9b9" v-if="record.status == 4">已离职</div>
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{ text }}</span>
              </template>
              {{ text }}
            </a-tooltip>
          </div>
        </span>
        <template slot="postType" slot-scope="text">{{ text !== null ? $store.state.enums.postTypeArr[text - 1] : "" }}</template>
        <template slot="gmtCreate" slot-scope="text">
          <span>{{ text ? moment(text).format("HH:mm:ss") : "" }}</span>
        </template>
        <span slot="sourceType" slot-scope="text">
          <span v-if="text === 1">网页端</span>
          <span v-if="text === 2">手机端</span>
          <span v-if="text === 3">更换用工单位</span>
        </span>
        <template slot="action" slot-scope="text, record">
          <a @click="detail(record)"> 详情 </a>
        </template>
      </a-table>
      <a-drawer
        title="添加员工"
        :width="580"
        :destroyOnClose="true"
        :visible="visibleEmpyleeDrawer"
        :wrap-style="{ overflow: 'auto' }"
        @close="onCloseDrawer('visibleEmpyleeDrawer')"
      >
        <a-tabs type="card" @change="callback">
          <a-tab-pane key="1" tab="添加员工">
            <a-col :gutter="24" style="margin: 10px 0 10px 0" v-if="isOut">
              <a-alert message="工价规则、招工劳务费规则修改提交后将生成一条新的规则。" banner closable />
            </a-col>
            <div class="emp-title">员工信息</div>
            <dynamic-Add-Employees
              @saveValueChange="saveValueChange"
              @cancelForm="cancelForm"
              :outEmpDetail="outEmpDetail"
              :title="title"
              :moduleCode="'onJob'"
            ></dynamic-Add-Employees>
          </a-tab-pane>
          <a-tab-pane key="2" tab="添加待入职">
            <a-col :gutter="24" style="margin: 10px 0 10px 0" v-if="isOut">
              <a-alert message="工价规则、招工劳务费规则修改提交后将生成一条新的规则。" banner closable />
            </a-col>
            <div class="emp-title">员工信息</div>
            <dynamic-Add-Employees
              @cancelForm="cancelForm"
              @saveValueChange="saveValueChange"
              :title="title"
              :moduleCode="'waitJob'"
            ></dynamic-Add-Employees>
          </a-tab-pane>
          <a-tab-pane key="3" tab="扫码入职">
            <a-spin :spinning="loadingcode" :delay="300">
              <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
                <a-form-item class="baseInfo-item" label="二维码有效期">
                  <div style="width: 200px; display: flex; align-items: center; font-size: 12px">
                    <a-input-number :min="1" v-model="timeDay" style="width: 100%; margin-right: 10px" @change="setAllContent" />
                    <div style="font-weight: 800; font-size: 14px">天</div>
                  </div>
                  <div>有效期：{{ FailureTime }}</div>
                </a-form-item>
                <a-form-item class="baseInfo-item" label="工作性质">
                  <a-select
                    style="width: 200px"
                    v-decorator="[
                      'postType',
                      {
                        rules: [{ required: true, message: '请选择工作性质' }]
                      }
                    ]"
                    placeholder="请选择工作性质"
                    :options="$store.state.enums.postTypeLst"
                    @change="postTypeSaoMaChange"
                    :default-value="SMDefault"
                    v-model="SMDefault"
                  />
                </a-form-item>
                <a-form-item class="baseInfo-item" label="渠道来源">
                  <a-select
                    v-model="channelDefault"
                    v-decorator="['postType', { rules: [] }]"
                    :default-value="channelDefault"
                    show-search
                    allowClear
                    placeholder="请选择渠道来源"
                    style="width: 200px"
                    @change="channelSaoMaChange"
                  >
                    <a-select-option
                      v-for="(item, index) in siteChannelList"
                      :key="`${item.value}_${index}`"
                      :value="`${item.value}_${item.label}`"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item v-if="typeValue === 1 && SMMubanList.length > 0" class="baseInfo-item" label="审批模板">
                  <a-select
                    style="width: 200px"
                    v-decorator="[
                      'postType',
                      {
                        rules: [{ required: true, message: '请选择审批模板' }]
                      }
                    ]"
                    placeholder="请选择审批模板"
                    @change="mubanSelect"
                    :default-value="muban"
                    v-model="muban"
                  >
                    <a-select-option v-for="item in SMMubanList" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item class="baseInfo-item" label="生成二维码">
                  <div style="width: 100%; display: flex; align-items: center; margin-top: 15px">
                    <img :src="codeimg" style="width: 150px; height: 150px" />
                    <div
                      style="position: absolute; z-index: 100; width: 150px; height: 150px; background-color: #252525aa"
                      v-if="refreshCode"
                      @click="creatCode"
                    >
                      <div
                        style="
                          cursor: pointer;
                          width: 100%;
                          height: 100%;
                          display: flex;
                          flex-flow: column;
                          align-items: center;
                          justify-content: center;
                          cursor: pointer;
                        "
                      >
                        <a-icon type="reload" :style="{ fontSize: '18px', color: '#fff' }" />
                        <span style="color: #ffffff">刷新二维码</span>
                      </div>
                    </div>
                  </div>
                  <div style="margin-top: 20px">
                    <a-button type="primary" @click="downloadCod" :disabled="refreshCode">下载二维码</a-button>
                  </div>
                </a-form-item>
              </a-form>
            </a-spin>
          </a-tab-pane>
        </a-tabs>
      </a-drawer>
      <a-modal title="添加待入职" :visible="isCloseMethod2" width="520px" :destroy-on-close="true" @cancel="handleCancel">
        <template slot="footer">
          <a-button v-if="isApproval" @click="handleCancel">关闭</a-button>
          <a-button v-if="!isApproval" key="submit" type="primary" ghost @click="finishEdit2">继续办理</a-button>
        </template>

        <div style="display: flex; flex-flow: column; align-items: center">
          <img v-if="!isApproval" style="width: 200px; height: 200px" src="@/assets/img/1.png" />
          <img v-else style="width: 200px; height: 200px" src="@/assets/img/2.png" />
          <span style="font-size: 20px; font-weight: 800">{{ !isApproval ? "提交成功" : "审批中" }}</span>
          <span style="color: #00000077; margin-top: 12px; margin-bottom: 12px">{{
            !isApproval ? "可在入职管理中选择确认到岗或者未到岗" : "已提交至审批流程"
          }}</span>
        </div>
      </a-modal>
      <a-modal title="选择审批模板" :visible="selectModel" width="520px" :destroy-on-close="true" @cancel="handleCancel">
        <template slot="footer">
          <a-button @click="handleCancel">取消</a-button>
          <a-button key="submit" type="primary" ghost @click="finishEdit3">下一步</a-button>
        </template>

        <div style="display: flex; flex-flow: column; align-items: center">
          <div
            v-for="(item, i) in templatesListGroup"
            :key="i"
            @click="temClick(item)"
            style="
              padding-top: 10px;
              padding-bottom: 10px;
              padding-right: 15px;
              width: 100%;
              display: flex;
              flex-flow: row;
              align-items: center;
              justify-content: space-between;
            "
            :class="{ backgroundC: item.select }"
          >
            <div style="display: flex; flex-flow: row">
              <img style="width: 52px; height: 52px; margin-right: 15px" src="@/assets/img/模板icon.png" />
              <div>
                <span style="display: flex; flex-flow: column; font-size: 16px; font-weight: 600">{{ item.typeName }}</span>
                <span style="color: #00000077">{{ item.typeDesc }}</span>
              </div>
            </div>
            <xq-icon type="icon-wancheng2" v-if="item.select" class="primary_color fs20"></xq-icon>
          </div>
        </div>
      </a-modal>
    </a-layout>
  </div>
</template>
<script>
import {
  pageOnJobEmpList,
  pageWaitLeave,
  selectEmpInfoPendingRelation,
  getEmpInfoCount,
  saveEmpInfoAndRule,
  getQueryCount,
  getQueryEmpPageList
} from "@/api/staff/staff";
import { getDepartmentInTree } from "@/api/department/department";
import { formatDateDefault, afterTime } from "@/utils/index";
import { isPhone } from "@/utils/validate";
import axios from "axios";
import dynamicAddEmployees from "./info/component/dynamicAddEmployees";

const columns = [
  {
    title: "姓名",
    dataIndex: "name",
    key: "name",
    ellipsis: true,
    scopedSlots: { customRender: "name" },
    width: 150
  },
  {
    title: "手机号",
    dataIndex: "phone",
    key: "phone",
    width: 150
  },
  {
    title: "身份证号",
    dataIndex: "idCard",
    ellipsis: true,
    width: 200
  },
  {
    title: "工作性质",
    dataIndex: "postType",
    ellipsis: true,
    width: 150,
    scopedSlots: { customRender: "postType" }
  },
  {
    title: "渠道来源",
    dataIndex: "channelName",
    ellipsis: true,
    width: 150,
    scopedSlots: { customRender: "channelName" }
  },
  {
    title: "创建时间",
    dataIndex: "gmtCreate",
    ellipsis: true,
    width: 150,
    scopedSlots: { customRender: "gmtCreate" }
  },
  {
    title: "录入人",
    dataIndex: "inputName",
    key: "inputName",
    scopedSlots: { customRender: "inputName" },
    width: 150
  },
  {
    title: "录入方式",
    dataIndex: "sourceType",
    key: "sourceType",
    scopedSlots: { customRender: "sourceType" },
    width: 150
  },
  {
    title: "操作",
    fixed: "right",
    dataIndex: "action",
    scopedSlots: { customRender: "action" },
    width: 100
  }
];

const formalType = ["试用", "正式"];
import { creatCode, loadAllChannelForSiteReq } from "@/api/staff/staff";
import { getModelList_isUse } from "@/api/billing/billing";
import { listByCompanyIdGet } from "./info/api";
import { mapState, mapGetters } from "vuex";
import { getChannels } from "@/api/outsourcing/outsourcing";
import moment from "moment";
export default {
  components: { dynamicAddEmployees },
  data() {
    return {
      siteChannelList: [],
      title: "新增",
      saveValueFrom: {},
      tempTemplate: undefined,
      templatesListGroup: [],
      loadingcode: false,
      codeimg: "",
      isApproval: true,
      selectModel: false,
      isCloseMethod2: false,
      refreshCode: false,
      timeDay: 7,
      tabKey: "1",
      typeValue: 1,
      isOut: false,
      show: true,
      channelId: "", // 渠道id
      empState: true,
      loading: false,
      searchVisible: false,
      formalType,
      isPhone,
      name: "",
      joinCityCode: "",
      joinCityName: "",
      searchForm: {},
      selectedRowKeys: [],
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      data: [],
      form: {},
      goOutsourcing: false,
      property: "",
      desc: false,
      outEmpDetail: null,
      depInfoOptions: [],
      selectTypeIndex: "all",
      selectStatus: "",
      visibleEmpyleeDrawer: false,
      // 转正日期
      proRegularDateShow: false,
      // 试用日期
      testDate: false,
      EmpState: null,
      empyleeForm: this.$form.createForm(this),
      // 员工排序
      staffSort: [
        { id: 1, name: "按姓氏排列", key: "namePinyin" },
        { id: 2, name: "按创建时间排列", key: "gmtCreate" },
        { id: 3, name: "按修改时间排列", key: "gmtModified" }
      ],
      gmtOrder: "gmtCreate",
      // 合同状态
      contractsStatus: [
        { id: 0, name: "合同未发起" },
        { id: 1, name: "待员工签署" },
        { id: 2, name: "待公司签署" },
        { id: 3, name: "签署完成" },
        { id: -1, name: "合同过期未签署" }
      ],
      sonStatus: "",
      isImprove: "",
      verified: "",
      newType: null,
      orders: {
        property: "",
        desc: false
      },
      SMMubanList: [],
      TypeOptions: [
        { value: 0, label: "无试用期" },
        { value: 1, label: "1个月" },
        { value: 2, label: "2个月" },
        { value: 3, label: "3个月" },
        { value: 4, label: "4个月" },
        { value: 5, label: "5个月" },
        { value: 6, label: "6个月及以上" }
      ],
      names: "张强",
      type: [],
      status: [
        { value: 1, label: "试用", name: "countWaitInformalAll", count: 0 },
        { value: 2, label: "正式", name: "countHasInformalAll", count: 0 }
      ],
      statuss: [
        { value: 3, label: "待入职", name: "countPre", count: 0 },
        { value: 4, label: "已离职", name: "countLeaveHas", count: 0 } //,
      ],
      tformalType: "",
      gender: "",
      chooseVisible: false,
      postType: "",
      SMDefault: 5,
      channelDefault: undefined,
      muban: undefined,
      FailureTime: "",
      highestEducation: [
        { value: 1, label: "小学" },
        { value: 2, label: "初中" },
        { value: 3, label: "中专" },
        { value: 4, label: "高中" },
        { value: 5, label: "大专" },
        { value: 6, label: "本科" },
        { value: 7, label: "硕士" },
        { value: 8, label: "博士" },
        { value: 9, label: "其他" }
      ],
      highestE: "",
      tPoliticalStatus: "",
      maritalStatus: [
        { value: 1, label: "已婚" },
        { value: 2, label: "未婚" },
        { value: 3, label: "离异" }
      ],
      tMaritalStatus: "",
      labelList: [],
      channelNames: [],
      channelName: "",
      tagTL: "",
      time: moment().format("YYYY-MM-DD"),
      nameOrPhoneOrCard: "",
      inputName: "",
      sortType: undefined,
      sourceType: 0,
      allCount: 0,
      pcCount: 0,
      appCount: 0,
      changeCount: 0
    };
  },
  computed: {
    ...mapState(["common"]),
    ...mapGetters(["isJF"]),
    cityList() {
      return this.common.cityList;
    },
    areaList() {
      return this.common.areaList;
    },
    columns() {
      return this.isJF ? columns.filter((item) => item.dataIndex !== "postType") : columns;
    }
  },
  filters: {
    filterType(val) {
      if (val === 1) {
        return "月";
      } else if (val === 2) {
        return "天";
      } else if (val === 3) {
        return "工时";
      } else {
        return "";
      }
    },
    bankPlaceFilter(val) {
      return val;
    }
  },
  watch: {},
  created() {
    this.type = JSON.parse(JSON.stringify(this.$store.state.enums.postTypeStatsInitLst));
    if (this.$route.query.name) {
      this.searchForm.nameOrPhoneOrEmail = this.$route.query.name;
    }
    if (this.$route.query.outEmpDetail) {
      this.outEmpDetail = JSON.parse(this.$route.query.outEmpDetail);
      this.outEmpDetail.idCard = this.outEmpDetail.idcard + "";
      if (this.outEmpDetail.joinDate) {
        this.outEmpDetail.joinDate = this.$moment(this.outEmpDetail.joinDate).format("YYYY-MM-DD");
      }
      const token = this.$store.state.auth.token;
      const data1 = this.outEmpDetail;
      Object.keys(data1).map((z) => {
        if (typeof data1[z] === "number" && data1[z].toString().length === 1) {
          data1[z] = data1[z] + "";
        }
        if (typeof data1[z] === "string" && data1[z].indexOf("https://") !== -1) {
          data1[z] = data1[z].split(",").filter((z) => `${z}?token=${token}`);
        }
      });
      this.outEmpDetail = data1;
      this.channelId = this.outEmpDetail.channelId;
    }
    if (this.$route.query.EmpState) {
      this.EmpState = this.$route.query.EmpState;
      this.isOut = true;
    }
    if (this.EmpState === "out") {
      this.visibleEmpyleeDrawer = true;
      this.empState = false;
      setTimeout(() => {
        this.empyleeForm.setFieldsValue({
          name: this.outEmpDetail.name,
          phone: this.outEmpDetail.phone,
          idCard: this.outEmpDetail.idcard,
          remark: this.outEmpDetail.remark,
          postType: 2
        });
      }, 500);
    }
    this.companyId = this.$store.state.hr.companyId;
    this.getTabNumber();
    getDepartmentInTree({ companyId: this.companyId }).then((res) => {
      this.depInfoOptions = this.tree(res.data[0].depChildList, "depChildList", true);
    });
    this.getData();
    this.getListByCompanyId();
    this.getChannelsList();
    this.loadSiteChannelList();
  },
  mounted() {},
  methods: {
    loadSiteChannelList() {
      loadAllChannelForSiteReq()
        .then((res) => {
          if (res.code === 200) {
            this.siteChannelList = res.data ? res.data.map((item) => ({ label: item.name, value: item.id })) : [];
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleMenuchange(e) {
      switch (e.key) {
        case "1":
          this.openChoose();
          break;
        case "2":
          this.gotoImportFile();
          break;
      }
    },
    openChoose() {
      this.chooseVisible = true;
    },
    chooseOk(e) {
      if (e === 1) {
        this.goto();
      } else if (e === 2) {
        this.$router.push({
          path: "/staff/batchEdit"
        });
      }
    },
    cancelForm() {
      this.visibleEmpyleeDrawer = false;
    },
    saveValueChange(data) {
      this.saveValueFrom = data;
      this.handleEmpyleeSubmitPre();
    },
    creatCode() {
      this.loadingcode = true;
      const par = {
        companyId: this.$store.state.hr.companyId,
        status: this.typeValue,
        validDays: this.timeDay,
        postType: this.SMDefault,
        channelId: this.channelDefault ? this.channelDefault.split("_")[0] : "",
        expireDate: this.timeDay ? new Date(this.FailureTime + ":00").getTime() : ""
      };
      if (this.typeValue === 1) {
        // 待入职
        par.flowId = this.muban;
        if (!par.flowId && this.SMMubanList.length > 0) {
          this.$notification["success"]({
            message: "success",
            description: "请选择审批模板"
          });
          return;
        }
      }

      creatCode(par)
        .then((res) => {
          this.loadingcode = false;
          if (res.data) {
            this.typeValue = res.data.status;
            this.codeimg = res.data.qrCodeUrl;
            this.timeDay = res.data.validDays;
            this.SMDefault = res.data.postType;
            const date = new Date(res.data.expireDate); // 时间戳转date
            this.FailureTime = this.moment(date).format("YYYY-MM-DD HH:MM");
            if (res.data.flowId === null) {
              this.muban = undefined;
            } else {
              this.muban = res.data.flowId;
            }

            this.refreshCode = false;
            if (!this.codeimg) {
              this.refreshCode = true;
            }
          } else {
            this.loadingcode = false;
            this.$notification["success"]({
              message: "success",
              description: "二维码创建失败"
            });
          }
        })
        .catch((err) => {
          console.log("error log --> ", err);
          this.loadingcode = false;
        });
    },
    temClick(item) {
      for (var i = 0; i < this.templatesListGroup.length; i++) {
        if (this.templatesListGroup[i].id === item.id) {
          this.templatesListGroup[i].select = true;
          this.tempTemplate = this.templatesListGroup[i].id;
        } else {
          this.templatesListGroup[i].select = false;
        }
      }
    },
    finishEdit2() {
      this.isCloseMethod2 = false;
      this.empyleeForm.resetFields();
      this.visibleEmpyleeDrawer = true;
    },
    finishEdit3() {
      this.handleEmpyleeSubmit();
      this.selectModel = false;
    },
    downloadCod() {
      window.open(this.codeimg + `?token=${this.$store.state.auth.token}`);
    },
    onTypeChange(e) {
      this.typeValue = e.target.value;
      this.refreshCode = true;
    },
    setAllContent(val) {
      this.timeDay = val;
      var d = new Date();
      const newTime = afterTime(this.moment(d, "YYYY-MM-DD"), this.timeDay);
      this.FailureTime = newTime + " " + d.getHours() + ":" + d.getMinutes();
      this.refreshCode = true;
    },
    callback(key) {
      this.loadingcode = false;
      this.tabKey = key;
      this.empyleeForm.resetFields();

      if (this.tabKey === "3") {
        this.loadingcode = true;
        const d = new Date();
        const newTime = afterTime(this.moment(d, "YYYY-MM-DD"), this.timeDay);
        this.FailureTime = newTime + " " + d.getHours() + ":" + d.getMinutes();
        this.creatCode();
      }
    },
    handleEmpyleeSubmitPre(e) {
      if (this.tabKey === "2") {
        // 待入职
        // 请求审批模板
        // 根据公司查询模板
        getModelList_isUse(this.companyId, "OnJob").then((res) => {
          this.templatesListGroup = [];
          for (var i = 0; i < res.data.length; i++) {
            this.templatesListGroup.push({
              id: res.data[i].id,
              select: false,
              typeName: res.data[i].typeName,
              typeDesc: res.data[i].typeDesc
            });
          }
          if (this.templatesListGroup.length > 0) {
            if (this.templatesListGroup.length === 1) {
              // 默认选中第一条
              this.tempTemplate = this.templatesListGroup[0].id;
              this.handleEmpyleeSubmit(e);
            } else {
              for (var k = 0; k < this.templatesListGroup.length; k++) {
                if (k === 0) {
                  this.templatesListGroup[k].select = true;
                } else {
                  this.templatesListGroup[k].select = false;
                }
              }
              // 显示第一条
              this.tempTemplate = this.templatesListGroup[0].id;
              this.selectModel = true;
            }
          } else {
            this.tempTemplate = undefined;
            this.handleEmpyleeSubmit(e);
          }
        });
      } else {
        this.handleEmpyleeSubmit(e);
      }
      this.getData();
    },
    handleEmpyleeSubmit(e) {
      var that = this;
      const salaryRuleAddDTO = {};
      const serviceFeeRuleAddDTO = {};
      const values = Object.assign(this.saveValueFrom);
      values.companyId = this.companyId;
      values.employType = 1;

      if (this.tabKey === "1") {
        values.status = 2; // 在职
      } else if (this.tabKey === "2") {
        values.status = 1; // 待入职
        if (this.tempTemplate) {
          values.flowId = this.tempTemplate;
        } else {
          values.flowId = "";
        }
      }
      if (this.outEmpDetail) {
        values.checkInId = this.outEmpDetail.checkInId;
      }

      values.joinCityCode = this.joinCityCode;
      values.joinCityName = this.joinCityName;
      values.formalType = values.formalType || 2;
      values.postType = values.postType || 5;
      values.joinDate = values.joinDate || formatDateDefault();
      values.preJoinDate = values.joinDate;
      values.probationDays = values.probationDays || 0;
      values.turnStraightDate = values.turnStraightDate || afterTime(values.joinDate, values.probationDays);
      saveEmpInfoAndRule(values, this.tabKey).then((res) => {
        if (values.postType === 2) {
          this.goOutsourcing = true;
          if (this.goOutsourcing === true) {
            this.$router.push({
              path: "/wages/file/outsourcingDetail",
              query: { showType: 1, state: "outsourcing", empId: res.data.id }
            });
          }
        } else {
          that.getData();
          that.getTabNumber();
          this.goOutsourcing = false;
          that.onCloseDrawer("visibleEmpyleeDrawer");
          if (this.tabKey === "2") {
            // 待入职
            if (this.tempTemplate) {
              this.isApproval = true;
            } else {
              // 添加成功
              this.isApproval = false;
            }
            this.isCloseMethod2 = true;
            this.selectStatusFunc(this.selectStatus);
          } else {
            this.$confirm({
              title: "添加成功",
              okText: "继续添加",
              cancelText: "返回员工列表",
              content: (h) => <div style="color:black;">是否继续添加员工？</div>,
              onOk() {
                that.addMember();
              }
            });
          }
        }
      });
    },
    // 清楚所有内容
    clear() {
      // 工价
      this.isOut = false;
      // 劳务费
      this.channelId = "";
      this.channelId = undefined;
    },
    handleCancel() {
      this.empyleeForm.resetFields();
      this.searchVisible = false;
      this.selectModel = false;
      this.isCloseMethod2 = false;
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 导出员工信息excel表
    download(i) {
      const token = this.$store.state.auth.token;
      let params = {};
      if (i === 2) {
        params = {
          isAll: 1,
          exportType: 2,
          operationEmpRecordQuery: {
            sourceType: this.sourceType ? this.sourceType : null,
            companyId: this.$store.state.hr.companyId,
            nameOrPhoneOrCard: this.nameOrPhoneOrCard,
            inputName: this.inputName,
            sortType: this.sortType ? this.sortType : null,
            date: this.time
          }
        };
      } else {
        const selectedRowKeys = this.data.filter((e) => {
          if (this.selectedRowKeys.includes(e.id)) {
            return e;
          }
        });
        const empInfoVOList = selectedRowKeys;
        params = {
          exportType: 2,
          empInfoVOList
        };
      }
      axios({
        url: `/hr/api/v1/statisticsPage/empTodayAddExport`,
        data: params,

        method: "post",
        responseType: "blob",
        headers: {
          token: token,
          "Content-Type": "application/json"
        }
      })
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", `${this.$store.state.hr.companyName}_` + "员工导出记录" + ".xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((err) => {
          console.log("error log --> ", err);
        });
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getData();
    },
    getMoment(date) {
      return date ? this.moment(date) : null;
    },
    selectStatusFunc(tag, current) {
      this.loading = true;
      this.sonStatus = "";
      this.tformalType = "";
      this.gender = "";
      this.postType = "";
      this.highestE = "";
      this.channelName = "";
      this.tPoliticalStatus = "";
      this.isImprove = "";
      this.tMaritalStatus = "";
      this.verified = "";
      this.pagination.current = current || 1;
      this.selectStatus = tag;
      this.searchForm.postType = undefined;
      this.selectTypeIndex = null;

      if (tag === 1) {
        this.searchForm.formalType = 1;
        this.searchForm.status = undefined;
        pageOnJobEmpList({
          companyId: this.companyId,
          ...this.searchForm,
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize
        })
          .then((res) => {
            if (res.data && res.data.entityCount) {
              this.pagination.total = res.data && res.data.entityCount;
            } else {
              this.pagination.total = 0;
            }
            if (res.data && res.data.entities && res.data.entities.length > 0) {
              res.data.entities.forEach((element) => {
                if (element.bankPlace) {
                  const values = this.buildValue(this.getLastAreaId(element.bankPlace));
                  const labels = values.map((item) => item.label);
                  element.bankPlace = labels.join("-");
                }
                if (element.customFields) {
                  for (var key in element.customFields) {
                    element[key] = element.customFields[key];
                  }
                }
              });
            }

            this.data = res.data && res.data.entities;
          })
          .finally(() => {
            this.loading = false;
          });
      } else if (tag === 2) {
        this.searchForm.formalType = 2;
        this.searchForm.status = undefined;
        pageOnJobEmpList({
          companyId: this.companyId,
          ...this.searchForm,
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize
        })
          .then((res) => {
            if (res.data && res.data.entityCount) {
              this.pagination.total = res.data && res.data.entityCount;
            } else {
              this.pagination.total = 0;
            }
            if (res.data && res.data.entities && res.data.entities.length > 0) {
              res.data.entities.forEach((element) => {
                if (element.bankPlace) {
                  const values = this.buildValue(this.getLastAreaId(element.bankPlace));
                  const labels = values.map((item) => item.label);
                  element.bankPlace = labels.join("-");
                }
                if (element.customFields) {
                  for (var key in element.customFields) {
                    element[key] = element.customFields[key];
                  }
                }
              });
            }
            this.data = res.data && res.data.entities;
          })
          .finally(() => {
            this.loading = false;
          });
      } else if (tag === 3) {
        this.searchForm.status = 1;
        this.searchForm.formalType = undefined;
        selectEmpInfoPendingRelation({
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize,
          companyId: this.companyId,
          ...this.searchForm
        })
          .then((res) => {
            if (res.data && res.data.entityCount) {
              this.pagination.total = res.data && res.data.entityCount;
            } else {
              this.pagination.total = 0;
            }
            if (res.data && res.data.entities && res.data.entities.length > 0) {
              res.data.entities.forEach((element) => {
                if (element.bankPlace) {
                  const values = this.buildValue(this.getLastAreaId(element.bankPlace));
                  const labels = values.map((item) => item.label);
                  element.bankPlace = labels.join("-");
                }
              });
            }
            this.data = res.data && res.data.entities;
          })
          .finally(() => {
            this.loading = false;
          });
      } else if (tag === 4) {
        this.searchForm.formalType = undefined;
        this.searchForm.status = 4;
        pageWaitLeave({
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize,
          companyId: this.companyId,
          ...this.searchForm
        })
          .then((res) => {
            if (res.data && res.data.entityCount) {
              this.pagination.total = res.data && res.data.entityCount;
            } else {
              this.pagination.total = 0;
            }
            if (res.data && res.data.entities && res.data.entities.length > 0) {
              res.data.entities.forEach((element) => {
                if (element.bankPlace) {
                  const values = this.buildValue(this.getLastAreaId(element.bankPlace));
                  const labels = values.map((item) => item.label);
                  element.bankPlace = labels.join("-");
                }
              });
            }
            this.data = res.data && res.data.entities;
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.data = [];
      }
    },
    getTabNumber() {
      getEmpInfoCount(this.$store.state.hr.companyId).then((res) => {
        const data = res.data;
        this.type.forEach((item, index) => {
          this.$set(this.type, index, {
            ...this.type[index],
            count: data[this.type[index].name]
          });
        });
        this.status.forEach((item, index) => {
          this.$set(this.status, index, {
            ...this.status[index],
            count: data[this.status[index].name]
          });
        });
        this.statuss.forEach((item, index) => {
          this.$set(this.statuss, index, {
            ...this.statuss[index],
            count: data[this.statuss[index].name]
          });
        });
      });
    },
    async onGetQueryCount() {
      try {
        const { data } = await getQueryCount({
          date: this.time ? this.time : this.moment().format("YYYY-MM-DD HH:mm:ss"),
          status: 1,
          companyId: this.$store.state.hr.companyId
        });
        this.allCount = data.allCount;
        this.pcCount = data.pcCount;
        this.appCount = data.appCount;
        this.changeCount = data.changeCount;
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onScreening(e) {
      this.sourceType = e;
      this.pagination.current = 1;
      this.getData();
    },
    getData(v) {
      if (v) {
        this.pagination.current = 1;
      }
      this.orders.property = this.gmtOrder;
      const data = {
        nameOrPhoneOrCard: this.nameOrPhoneOrCard,
        inputName: this.inputName,
        sortType: this.sortType ? this.sortType : null,
        date: this.time,
        sourceType: this.sourceType ? this.sourceType : null,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        companyId: this.companyId,
        "orders[0].property": "gmtCreate",
        "orders[0].desc": true
      };
      this.loading = true;
      this.onGetQueryCount();
      getQueryEmpPageList(data)
        .then((res) => {
          if (res.data && res.data.entityCount) {
            this.pagination.total = res.data && res.data.entityCount;
          } else {
            this.pagination.total = 0;
          }
          if (res.data && res.data.entities) {
            res.data.entities.map((item) => {
              if (item.isImprove == null) {
                item.isImprove = false;
                // item.isImprove = true
              }
            });
          }
          if (res.data && res.data.entities && res.data.entities.length > 0) {
            res.data.entities.forEach((element) => {
              if (element.bankPlace) {
                const values = this.buildValue(this.getLastAreaId(element.bankPlace));
                const labels = values.map((item) => item.label);
                element.bankPlace = labels.join("-");
              }
              if (element.customFields) {
                for (var key in element.customFields) {
                  element[key] = element.customFields[key];
                }
              }
            });
          }
          this.data = res.data && res.data.entities;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    getLastAreaId(values) {
      if (Array.isArray(values)) {
        return values[values.length - 1];
      } else {
        return values.split(",").slice(-1)[0];
      }
    },
    buildValue(id, needRecursion = true) {
      id = parseInt(id);
      const index = this.common.areaSourceList.findIndex((item) => item.id === parseInt(id));
      if (index > -1) {
        const item = this.common.areaSourceList[index];
        const val = {
          value: id,
          label: item.name
        };
        if (needRecursion && item.parentId > 0) {
          return this.buildValue(item.parentId).concat([val]);
        } else {
          return [val];
        }
      }
      return [];
    },
    detail(row) {
      const data = {
        queryType: 1,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        companyId: this.companyId,
        ...this.searchForm,
        "orders[0].property": this.gmtOrder,
        "orders[0].desc": this.gmtOrder !== "namePinyin"
      };
      const data1 = JSON.parse(JSON.stringify(data));
      data1.joinDateMoment = null;
      this.$router.push({
        path: "/staff/detail",
        query: {
          searchFormData: data1,
          id: row.id,
          userId: row.userId,
          pageType: "todayAdd"
        }
      });
    },
    goto() {
      this.$router.push({
        path: "/staff/upload"
      });
    },
    gotoImportFile() {
      this.$router.push({
        path: "/staff/uploadFile"
      });
    },
    onCloseDrawer(tag) {
      this[tag] = false;
    },
    addMember() {
      this.proRegularDateShow = false;
      this.testDate = false;
      this.joinCityCode = null;
      this.joinCityName = null;
      this.empyleeForm.resetFields();
      this.visibleEmpyleeDrawer = true;
      this.clear();
      // 请求二维码审核模板
      getModelList_isUse(this.companyId, "OnJob").then((res) => {
        this.SMMubanList = [];
        for (var i = 0; i < res.data.length; i++) {
          this.SMMubanList.push({
            value: res.data[i].id,
            label: res.data[i].typeName
          });
        }
        if (this.SMMubanList.length > 0) {
          // 默认选中第一条
          this.muban = this.SMMubanList[0].value;
        } else {
          this.muban = undefined;
        }
      });
    },
    postTypeSaoMaChange(value) {
      this.SMDefault = value;
      this.refreshCode = true;
    },
    channelSaoMaChange(value) {
      this.channelDefault = value;
      this.refreshCode = true;
    },
    mubanSelect(value) {
      this.muban = value;
      this.refreshCode = true;
    },
    tree(array, childKey, onlyLastChild) {
      if (array === null || array.length < 1) {
        return [];
      }
      array.map((item, index) => {
        item["value"] = item.id;
        item["key"] = item.id;
        item["label"] = item.name;
        item["children"] = item[childKey];

        if (item.leave !== 3) {
          item["disabled"] = onlyLastChild;
        }

        if (item.children) {
          this.tree1(item.children, childKey, onlyLastChild);
        }
      });
      return array;
    },
    tree1(array, childKey, onlyLastChild) {
      if (array === null || array.length < 1) {
        return [];
      }
      array.map((item, index) => {
        item["value"] = item.id;
        item["key"] = item.id;
        item["label"] = item.name;
        item["children"] = item[childKey];

        if (item.children) {
          this.tree1(item.children, childKey, onlyLastChild);
        }
      });
      return array;
    },
    getListByCompanyId() {
      listByCompanyIdGet({ companyId: this.$store.state.hr.companyId })
        .then(({ data }) => {
          this.labelList = data;
        })
        .catch((err) => {
          console.log("error log --> ", err);
        });
    },
    getChannelsList() {
      getChannels({
        pageNo: 1,
        pageSize: 1000
      }).then((res) => {
        this.channelNames = res.data.entities;
      });
    }
  }
};
</script>
<style lang="scss">
.chooseBox {
  width: 560px;
  height: 90px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .choose {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    flex-direction: column;
  }
}
.chooseTitle {
  font-size: 16px;
  font-weight: 500;
  padding: 4px;
  // color: #3c3d43;
}
.chooseContent {
  font-size: 12px;
  font-weight: 400;
  padding: 4px;
  // color: #767885;
}
// .chooseBox:hover {
//   width: 560px;
//   height: 90px;
//   background: #ffffff;
//   border-radius: 4px;
//   border: 1px solid var(--primary) !important;
//   color: var(--primary) !important;
// }
// .chooseTitle:hover {
//   font-size: 16px;
//   font-weight: 500;
//   color: var(--primary);
// }
// .chooseContent:hover {
//   font-size: 12px;
//   font-weight: 400;
//   color: var(--primary);
// }
.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab-active {
  color: var(--primary);
  border-color: var(--primary) !important;
  border-bottom: 1px solid #fff !important;
}

// .ant-drawer-body {
//   // padding-bottom: 50px !important;
// }
</style>
<style lang="scss" scoped>
.overview-select-tag-name {
  cursor: pointer;
  margin: 5px;
  color: #666666;
}
.overview-select-tag {
  background-color: #fff !important;
  color: var(--primary) !important;
  border: 1px solid var(--primary);
  cursor: pointer;
  margin: 5px;
}
.overview-tag-wrapper {
  ::v-deep .ant-tag {
    .anticon-close {
      color: var(--primary);
    }
  }
}
.baseInfo-item {
  display: flex;
  flex-flow: row;
  // align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}
.backgroundC {
  background-color: var(--primary10);
}
.submitBox {
  position: absolute;
  right: 0;
  bottom: 0;
  height: 70px;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding-top: 20px;
  background: #fff;
  text-align: center;
  // z-index: 1;
}
.emp-title {
  padding-left: 24px;
  line-height: 48px;
  height: 48px;
  background: rgba(250, 250, 250, 1);
}

>>> .anticon-plus {
  font-size: 12px;
}

.typeList > div {
  cursor: pointer;
}

.pageName {
  font-size: 16px;
  color: #333;
  padding-left: 18px;
}
.typeList {
  text-align: center;
  border: 1px solid #e8e8e8;
  height: 100px;
  // line-height: ;

  h5 {
    font-size: 14px;
    padding-bottom: 5px;
    color: #9c9c9c;
  }
  .number {
    font-size: 18px;
    font-weight: 500;
  }
  .line:after {
    content: "";
    position: absolute;
    left: auto;
    top: 11px;
    bottom: auto;
    right: 0;
    height: 38px;
    width: 1px;
    background-color: #e8e8e8;
  }
}
.selectType {
  h5 {
    color: var(--primary);
  }
  span {
    color: var(--primary);
  }
}
.overview-no-select-tag {
  background-color: #fff;
  cursor: pointer;
  margin: 5px;
}
.rowForm {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  white-space: nowrap;
  align-items: center;
  height: 50px;
}
.shu {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  .shuxian {
    width: 3px;
    height: 20px;
    background: var(--primary);
  }
}
.deleteIcon:hover {
  color: #fa5051;
}
.addIcon {
  color: var(--primary);
}
.tags-tit {
  color: #3c3d43;
  margin-bottom: 10px;
  font-weight: bold;
}
.tags-boxs {
  display: flex;
  flex-wrap: wrap;
  width: 184px;
  .tags-item {
    padding: 0 10px;
    height: 20px;
    line-height: 20px;
    background: #f2f2f2;
    border-radius: 2px;
    margin-right: 8px;
    margin-bottom: 8px;
  }
}
.today-tags {
  position: relative;
  padding-left: 10px;
  .tags-item {
    position: absolute;
    top: -8px;
    left: -42px;
    font-size: 12px;
    width: 86px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    color: #fff;
    -webkit-transform: rotateZ(-60deg);
    -ms-transform: rotate(-60deg);
    transform: rotateZ(-48deg);
  }
}
.tags {
  width: 46px;
  height: 20px;
  background: #f2f2f2;
  border-radius: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
  display: inline-block;
}
.tags-d {
  margin-left: 5px;
}
.t-row {
  font-size: 16px;
  display: flex;
  .t-col {
    color: #767885;
    margin-right: 24px;
    cursor: pointer;
    span {
      color: var(--primary);
    }
  }
}
</style>
